package tcp

import (
	"gomonitor-server/src/db"
	"gomonitor-server/src/mylog"
	"gomonitor-server/src/tcp/connectioncount"
	"gomonitor-server/src/tcp/message"
	"net"
	"strconv"
)

var connectionMap = make(map[string]net.Conn)
var msgHandlerMap = make(map[string]*message.MessageHandler)

func handleConnection(msgFrom byte, conn net.Conn) {
	/***
	*TCP数据包格式： 标识|上(A)下(B)行|类型｜长度｜数据｜和校验
	*-----------------------------------------------------
	*FEED	|	B	|	类型	|	长度	|	 数据	|	 和校验
	*4		|	1	|	1	|	4	|	xxx		|	 4
	*-----------------------------------------------------
	*类型含义:
	*0:上报:主机名，回复：服务器主机名
	 */
	msgHandler := new(message.MessageHandler)
	connectionMap[conn.RemoteAddr().String()] = conn
	msgHandlerMap[conn.RemoteAddr().String()] = msgHandler

	buffer := make([]byte, 1024)
	var bufferPool []byte
	for {
		mylog.Logger.Debugf("开始读取连接%s数据", conn.RemoteAddr().String())
		n, err := conn.Read(buffer)
		mylog.Logger.Debugf("结束读取连接%s数据", conn.RemoteAddr().String())
		if err != nil {
			err = conn.Close()
			if err != nil {
				mylog.Logger.Warningf("关闭连接:%s失败..%s", conn.RemoteAddr().String(), err.Error())
			} else {
				mylog.Logger.Debugf("关闭连接:%s成功", conn.RemoteAddr().String())
			}
			connectioncount.DisConnection(conn)
			delete(connectionMap, conn.RemoteAddr().String())
			delete(msgHandlerMap, conn.RemoteAddr().String())
			mylog.Logger.Errorf("客户端%s断开连接:%s", conn.RemoteAddr().String(), err.Error())
			host, port, err := net.SplitHostPort(conn.RemoteAddr().String())
			if err != nil {
				mylog.Logger.Error("error reading from tcp: ", err)
				return
			}
			portInt, err := strconv.ParseUint(port, 10, 32)
			if err != nil {
				portInt = 0
			}
			db.RecordConnectLog(host, int(portInt), 2)
			break
		}
		if n == 0 {
			continue
		} else {
			mylog.Logger.Debugf("读取连接%s到数据包长度:%d,缓冲池数据长度:%d", conn.RemoteAddr().String(), n, len(bufferPool))
		}
		processMessage(msgHandler, msgFrom, n, buffer, &bufferPool, conn)
	}
}
